from django.views import View
# 导入返回响应
from SaaSDevelTool.data_return_response import create_response
# 导入错误信息装饰器
from SaaSDevelTool.data_return_response import error_message_detection
# 导入分页
from SaaSDevelTool.data_mysql_data import db
# 查询当前参数是否是int类型
from SaaSDevelTool.data_operation import is_number

"""
添加对应的功能包
"""


class SaaSDevelModelPackAgeCreate(View):
    @error_message_detection
    def post(self, request):
        # 获取功能包名称
        package_name = request.POST.get("package_name")
        # 获取功能包大模块
        model_id = request.POST.get("model_id")
        # 获取功能包地址
        package_images = request.POST.get("package_images")
        # 获取功能包备注
        package_remark = request.POST.get("package_remark")
        # 判断参数是否完整
        if not all([package_name, model_id, package_images]):
            # 返回对应的大模块
            return create_response(code=400, msg="添加失败，功能包名称,功能包所属大模块,功能包图标不能为空。")

        # 判断功能包名称
        if len(package_name) > 30 and len(package_name) < 3:
            return create_response(code=400, msg="添加失败，功能包名称最大不得超过30字，最小不得小于3个字。")

        # 判断大模块参数
        if not is_number(model_id):
            return create_response(code=400, msg="添加失败，大模块参数格式传递错误。")

        # 判断数据是否存在
        query_sum_package_table_sql = """
            SELECT 
                package_name,
                model_id 
            FROM 
                db_saas_center.sum_package_table 
            WHERE 
                package_name = '{}' 
            AND 
                model_id = {}
            ;""".format(package_name, model_id)
        query_sum_package_table_data = db.findOne(query_sum_package_table_sql)

        # 如果当前大模块的功能包已存在
        if query_sum_package_table_data:
            # 返回对应的响应
            return create_response(code=400,
                                   msg="添加失败，当前功能包所在大模块中已包含【{}】名称的大模块，请更换名称后操作。"
                                   .format(package_name))

        # 拼接sql语句进行操作
        create_sum_package_table_sql = """
            INSERT INTO 
                db_saas_center.sum_package_table(
                    package_name, 
                    package_remark, 
                    model_id, 
                    package_images)
            VALUES
                ('{}', '{}', {},'{}')
            ;""".format(package_name, package_remark, model_id, package_images)
        # 执行sql语句进行添加
        db.update(create_sum_package_table_sql)

        # 返回对应的响应
        return create_response(code=200, msg="功能包基础信息创建成功。")
